package com.raos.example.redis.networkmodel.reactorthread;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 多线程Reactor 模型（高性能I/O设计模式）
 * 连接请求处理授体
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/7/24 21:04
 **/
public class MultiAcceptor implements Runnable {

    private final Selector selector;
    private final ServerSocketChannel serverSocketChannel;

    public MultiAcceptor(Selector selector, ServerSocketChannel serverSocketChannel) {
        this.selector = selector;
        this.serverSocketChannel = serverSocketChannel;
    }

    @Override
    public void run() {
        SocketChannel channel;

        try {
            // 得到一个客户端连接
            channel = serverSocketChannel.accept();
            System.out.println(channel.getRemoteAddress() + ":收到一个客户端连接");
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ, new MultiDispatchHandler(channel));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
